const forge = require('node-forge');
const fs = require('fs');

// 加载CA证书和私钥
const caCertPem = fs.readFileSync('./ssl-new/certs/ca.pem', 'utf8');
const caKeyPem = fs.readFileSync('./ssl-new/keys/ca.private.key', 'utf8');
const caCert = forge.pki.certificateFromPem(caCertPem);
const caKey = forge.pki.privateKeyFromPem(caKeyPem);

// 生成域名密钥对
const keys = forge.pki.rsa.generateKeyPair(2048);
const cert = forge.pki.createCertificate();

cert.publicKey = keys.publicKey;
cert.serialNumber =  "01"//String(Date.now());
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);

// 设置证书的域名
const attrs = [
  { name: 'commonName', value: 'localhost' },
  { name: 'countryName', value: 'US' },
  { shortName: 'ST', value: 'California' },
  { name: 'localityName', value: 'San Francisco' },
  { name: 'organizationName', value: 'Example Inc.' },
  { shortName: 'OU', value: 'IT' }
];
cert.setSubject(attrs);
cert.setIssuer(caCert.subject.attributes);
// 证书设置
cert.setExtensions([
    {
      name: "basicConstraints",
      critical: true,
      cA: false,
    },
    {
      name: "keyUsage",
      keyCertSign: true,
      digitalSignature: true,
      nonRepudiation: true,
      keyEncipherment: true,
      dataEncipherment: true,
    },
    {
      name: "extKeyUsage",
      serverAuth: true,
      clientAuth: true,
      codeSigning: true,
      emailProtection: true,
      timeStamping: true,
    },
    {
      name: "nsCertType",
      client: true,
      server: true,
      email: true,
      objsign: true,
      sslCA: true,
      emailCA: true,
      objCA: true,
    },
    {
      name: "subjectAltName",
      // 这里填多个域名或者 ip
      altNames: [
        {
          type: 2, // DNS
          value: "localhost",
        },
        {
          type: 7, // ipv4
          ip: "127.0.0.1",
        },
        {
          type: 7, // ipv6
          ip: "[::1]",
        },
      ],
    },
    {
      name: "subjectKeyIdentifier",
    },
  ]);
// 签名证书
cert.sign(caKey, forge.md.sha256.create());

// 将证书和私钥转换为PEM格式
const pemCert = forge.pki.certificateToPem(cert);
const pemKey = forge.pki.privateKeyToPem(keys.privateKey);

// 保存证书和私钥
fs.writeFileSync('./localhost-cert.cert', pemCert);
fs.writeFileSync('./localhost-key.key', pemKey);

console.log('Domain certificate and key generated successfully');
